<html>
  <head>
    <script type="text/javascript" src="/js/dao.js"></script>
  </head>
  <body>
  <script>
//=======================================================
//listener for content scripts
//=======================================================
chrome.extension.onRequest.addListener(
    function(request, sender, sendResponse) {
	log("request action : " + request.action);
	switch(request.action) {
	    case "getAccounts" :
		sendResponse(Service.getAccounts());
		break;
	    case "onTabLogin" :
		sendResponse(onTabLogin(sender.tab.id));
		break;
	    case "onTabLogout" :
		sendResponse(onTabLogout(sender.tab.id));
		break;
	    case "setUsernameToSignIn" :
		sendResponse(Service.setAccountToSignIn(request.username));
		break;
	    case "getAccountToSignIn" :
		sendResponse(Service.getAccountToSignIn());
		break;
	    case "getPasswordFor" :
		sendResponse(DomainDao.getPassword(request.account));
		break;
	    case "getAdSenseAutoSignInValue" :
		sendResponse(getAdSenseAutoSignInValue());
		break;
	    case "setAccount" :
		sendResponse(Service.setAccount(request.account));
		break;
	}
    }  
);

//=======================================================
//google ajax request
//=======================================================       
var ACCOUNT_LOGGED_IN_STATUS = false;
var TIMEOUT = 2000;

function onTabLogin(tabId) {
        log("updateTabs onTabLogin with id " + tabId);
        if(ACCOUNT_LOGGED_IN_STATUS == false) {
                setTimeout("sendBroadcast(" + tabId + ")", TIMEOUT);
                ACCOUNT_LOGGED_IN_STATUS = true;
        }
        return;
}
function onTabLogout(tabId) {
        log("updateTabs onTabLogout with id " + tabId);
        if(ACCOUNT_LOGGED_IN_STATUS) {
                setTimeout("sendBroadcast(" + tabId + ")", TIMEOUT);
                ACCOUNT_LOGGED_IN_STATUS = false;
        }
        return;
}
function sendBroadcast(tabId) {
        log("sendBroadcast");
        chrome.tabs.getAllInWindow(null, function(tabs) {
                for (var i = 0; i < tabs.length; i++) {
                        log("checking i = " + i + " : " + tabs[i].id);
                        if(tabId != tabs[i].id) {
                                chrome.tabs.sendRequest(tabs[i].id, {tabid: tabs[i].id}, function(response) {
                                log("message sent to " + tabs[i].id);
                                });
                        }
            }
        });
}
//======================================================================
//log abstraction
//======================================================================
function log(msg) {
        console.info(msg);
}
</script>
</body>
</html>
